package com.qilin.hscs.hm.mqtt.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.qilin.hscs.hm.convert.BaseConvert;
import com.qilin.hscs.hm.convert.DTO2DOConvert;
import com.qilin.hscs.hm.dao.*;
import com.qilin.hscs.hm.dto.MuticontrollerDeviceDto;
import com.qilin.hscs.hm.mqtt.service.MutiControllerDeviceService;
import com.qilin.hscs.hm.mqtt.service.MutiControllerService;
import com.qilin.hscs.hm.mqtt.service.common.ServiceCommon;
import com.qilin.hscs.hm.pojo.*;
import com.qilin.hscs.hm.util.MqttResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.core.jackson.ListOfMapEntrySerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("MutcontollerDevice")
public class MutiControllerDeviceServiceImpl extends ServiceCommon implements MutiControllerDeviceService {

    private JSONObject msgObj;

    @Autowired
    private MutcontollerDeviceRepository repository;
    @Autowired
    private MuticontrollerRepository muticontrollerRepository;

    @Autowired
    private DeviceRepository deviceRepository;

    /**
     * 获取多控里所有设备
     */
    @Override
    public void findTotalDeviceInMutiController() {
        log.info("获取多控里所有设备");
        JSONObject dataObj = msgObj.getJSONObject("data");
        String phone = dataObj.getString("phone");
        JSONObject muticontrollerDeviceObj = dataObj.getJSONObject("muticontroller");
        Integer id = muticontrollerDeviceObj.getInteger("id");
        Map<String, Object> data = new HashMap<>();
        data.put("phone",phone);
        ArrayList<Map<String, Object>> list =new ArrayList<>();
        List<MuticontollerDevice> muticontollerDevices = this.repository.findByMuticontrollerId(id);
       for (MuticontollerDevice muticontollerDevice:muticontollerDevices){
           int dId = muticontollerDevice.getDeviceId();
           List<Device> deviceList = deviceRepository.findById(dId);
           for (Device device:deviceList){
               Map<String, Object> devices = new HashMap<>();
               devices.put("id",device.getId());
               devices.put("uid", BaseConvert.string2IntegerArr(device.getUid()));
               devices.put("ieee",BaseConvert.string2IntegerArr(device.getIeee()));
               devices.put("ep",device.getEp());
               devices.put("ept",device.getEpt());
               devices.put("icon",device.getIcon());
               devices.put("isShow",device.getIsShow());
               devices.put("isStar",device.getIsStar());
               devices.put("name",device.getName());
               devices.put("num",device.getNum());
               devices.put("sts",device.getSts());
               devices.put("roomId",device.getRoomId());
               list.add(devices);
           }
           data.put("devices",list);
           msg= MqttResultUtil.getResult(15001, 0, data);
       }
    }

    /**
     * 添加被控目标组的设备
     */
    @Override
    public void addDeviceInMutiController() {
        log.info("添加被控目标组的设备");
        JSONObject dataObj = msgObj.getJSONObject("data");
        Integer gid = dataObj.getInteger("gid");
        Integer ep = dataObj.getInteger("ep");
        String uid = StringUtils.join(dataObj.getJSONArray("uid"), ",");
        String ieee = StringUtils.join(dataObj.getJSONArray("ieee"), ",");
        Device device = deviceRepository.findByIeeeAndEpAndUid(ieee, ep ,uid);
        MuticontollerDevice m = new MuticontollerDevice();
//        m.setMuticontrollerId(mutiController.getId());
        m.setDeviceId(device.getId());
        this.repository.save(m);
        Map<String, Object> data = new HashMap<>();
        data.put("gid",gid);
        data.put("uid",BaseConvert.string2IntegerArr(uid));
        data.put("ieee",BaseConvert.string2IntegerArr(ieee));
        data.put("ep",ep);
//        data.put("mutiController",mutiController.getId());
        data.put("device",device.getId());
        msg= MqttResultUtil.getResult(15002, 0, data);
    }

    /**
     * 删除被控目标组的设备
     */
    @Override
    public void delDeviceInMutiController() {
        log.info("删除被控目标组的设备");
        JSONObject dataObj = msgObj.getJSONObject("data");
//        Integer gid = dataObj.getInteger("")
    }

    @Override
    public void handle() {
        switch (cmd) {
            case 14001:
                try {
                    findTotalDeviceInMutiController();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isflushToGateway(false);
                flush();
                break;
            case 14002:
                try {
                    addDeviceInMutiController();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isflushToGateway(false);
                flush();
                break;
            case 14003:
                try {
                    delDeviceInMutiController();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                isflushToGateway(true);
                flush();
                break;
            default:
        }
    }


    @Override
    public void initailData(){
        try {
            msgObj = JSON.parseObject(msg);
            dataObj = msgObj.getJSONObject("data");
        } catch (JSONException je) {
            log.warn("传输过来的json字符串有误，主机无法解析 错误详细情况为={}", je.getStackTrace());
        }
        cmd = msgObj.getInteger("cmd");
        if (topicVar != null) {
            if (!topicVar.contains("/rsp")) {
                phone = msgObj.getString("phone");
            }
        }
    }
}
